package com.diao.myhub.util;

import com.diao.myhub.model.dto.TagDTO;
import com.diao.myhub.enums.TagTypeEnum;
import com.diao.myhub.model.po.Tag;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public final class TagUtils {
    public static List<TagDTO> mappingTagFormDb(List<Tag> dbList) {
        Map<Integer, List<Tag>> tagGroup = dbList.stream()
                .sorted(TAG_TREAD_COMPARATOR)
                .collect(Collectors.groupingBy(Tag::getType));
        Map<Long, List<Tag>> cGroup;
        int tagTypeCode = TagTypeEnum.TAG.getTypeCode();
        if (tagGroup.containsKey(tagTypeCode)) {
            List<Tag> secondaries = tagGroup.get(tagTypeCode);
            cGroup = secondaries.stream().collect(Collectors.groupingBy(Tag::getPid));
        } else {
            cGroup = Collections.emptyMap();
        }
        int categoryTypeCode = TagTypeEnum.CATEGORY.getTypeCode();
        if (tagGroup.containsKey(categoryTypeCode)) {
            List<Tag> primary = tagGroup.get(categoryTypeCode);
            return primary.stream().map(pTag -> {
                TagDTO tagDTO = new TagDTO();
                tagDTO.setCategoryId(pTag.getId());
                List<Tag> tags = cGroup.computeIfAbsent(pTag.getId(), k -> Collections.emptyList());
                tagDTO.setTags(tags.stream().map(Tag::getName).collect(Collectors.toList()));
                tagDTO.setCategoryName(pTag.getName());
                return tagDTO;
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    public static final Comparator<Tag> TAG_TREAD_COMPARATOR = (t1, t2) -> {
        Long trendT1 = t1.getTrend();
        Long trendT2 = t2.getTrend();
        if (trendT1 == null || trendT2 == null) {
            return -1;
        }
        return trendT2.compareTo(trendT1);
    };
}
